<template>
	<view>
		<view class="upload-list">
			<view class="upload-item select-image" v-if="uploadImageShow && !disabled" @click="chooseImages">
				<image src="/static/images/add.png" mode="widthFix" class="img"></image>
			</view>
			
			<view class="upload-item" v-for="(item, index) in fileList" :key="index">
				<image @click="previewImages(index)" :src="item.src" mode="aspectFill" class="img"></image>
				<image v-if="!disabled" @click.stop="deleteImage(index)" src="/static/images/delete-image.png" mode="widthFix" class="delete-icon"></image>
			</view>
		</view>
	</view>
</template>

<script>
	import {uploadImage} from '@/api/upload.js';
	export default {
		name:"image-upload",
		data() {
			return {
				fileList: []
			};
		},
		computed: {
			uploadImageShow() {
				return this.total > this.fileList.length;
			},
			currentTotal() {
				return this.total - this.fileList.length;
			}
		},
		props: {
			total: {
				type: Number,
				default: 1
			},
			list: {
				type: Array,
				default: () => []
			},
			disabled: {
				type: Boolean,
				default: () => false
			}
		},
		watch: {
			list() {
				this.fileList = this.list;
			}
		},
		methods: {
			deleteImage(index) {
				this.fileList.splice(index, 1);
				this.fileChange();
			},
			async chooseImages() {
				let [err, res] = await uni.chooseImage({
					count: this.currentTotal,
					sizeType: 'compressed',
					extension: ['.png', '.jpg', '.jpeg']
				});
				if (err !== null) {
					return;
				}
				let tempFilePaths = res.tempFilePaths || [];
				if (!tempFilePaths) {
					return;
				}
				for (let tmp of tempFilePaths) {
					await this.uploadImage(tmp);
				}
			},
			fileChange() {
				this.$emit('change', this.fileList);
			},
			/**
			 * 执行文件上传操作
			 * @param {Object} filePath
			 */
			async uploadImage(filePath) {
				try{
					let res = await uploadImage(filePath);
					this.fileList.push({
						// src: this.$getImageUrl(res.data.image),
						src: res.data.image,
						path: res.data.image
					});
					this.fileChange();
				}catch(e){
					console.log(e);
					//TODO handle the exception
				}
			},
			previewImages(index) {
				uni.previewImage({
					urls: this.fileList.map(item => item.src),
					current: index
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.upload-list {
		width: 100%;
		display: grid;
		grid-gap: 15rpx;
		grid-template-columns: repeat(auto-fill, 162rpx);
		
		.upload-item {
			width: 162rpx;
			height: 162rpx;
			border-radius: 8rpx;
			overflow: hidden;
			position: relative;
			
			.img {
				width: 100%;
				height: 100%;
			}
			
			.delete-icon {
				position: absolute;
				width: 40rpx;
				height: 40rpx;
				top: 0;
				right: 0;
			}
		}
	}
</style>